package gw.com.android.ui.views;

import android.content.Context;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.bumptech.glide.Glide;
import com.gwtsz.gts2.hx.R;

/**
 * @author jett
 * @since 2017-10-17.
 */
public class PickedImageItem extends RelativeLayout {

    private OnRemoveListener listener;
    private ImageView iv;
    public String resource;

    public PickedImageItem(Context context) {
        super(context);
        init();
    }

    public PickedImageItem(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public PickedImageItem(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        iv = new ImageView(getContext());
        //iv.setImageResource(R.mipmap.order_share);
        iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
        RelativeLayout.LayoutParams param = new RelativeLayout.LayoutParams(dp2px(80), dp2px(80));
        param.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        addView(iv, param);

        ImageView ivDel = new ImageView(getContext());
        ivDel.setImageResource(R.mipmap.a_feedback_delete);
        RelativeLayout.LayoutParams delParam = new RelativeLayout.LayoutParams(dp2px(20), dp2px(20));
        delParam.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        addView(ivDel, delParam);

        ivDel.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (listener != null) {
                    listener.onRemove(PickedImageItem.this);
                }
            }
        });
    }

    public void setResource(String path) {
        this.resource = path;
        Glide.with(getContext()).load(path).into(iv);
    }

    public void reset() {
        this.resource = null;
        iv.setImageResource(0);
        this.listener = null;
    }

    public void setOnRemoveListener(OnRemoveListener l) {
        this.listener = l;
    }

    interface OnRemoveListener {
        void onRemove(PickedImageItem item);
    }

    private int dp2px(float dp) {
        DisplayMetrics metrics = getContext().getResources().getDisplayMetrics();
        return (int) (dp * (metrics.densityDpi / 160f) + 0.5F);
    }

}
